<template>
  <div id="qiTatVsItemDiv">
    <Breadcrumb content="周转时间具体项目设置" />
    <div class="bodyContent">
      <Splitpanes>
        <!-- 左侧表格  -->
        <Pane size="15">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">项目类型</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="tloading" @click="findTatItemTypeList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="tatItemTypeTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="tatItemTypeList" :loading="tloading" @current-change="tatItemTypeRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="code" title="项目类型代码"></vxe-column>
              <vxe-column field="name" title="项目类型名称">
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <!-- 右侧表单 -->
        <Pane size="15">
          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">具体项目</div>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="sloading" @click="findTatSpecItemList"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="sampleTypeTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="tatSpecItemList" :loading="sloading" @current-change="tatSpecItemRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="seq" title="序号" width="30"></vxe-column>
              <vxe-column field="code" title="项目代码"></vxe-column>
              <vxe-column field="name" title="项目名称">
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="40">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchTatItemForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findQiTatVsItemList" @keyup="keyupTatItemEnter" @search-click="findQiTatVsItemList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="ploading" @click="findQiTatVsItemList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" @click="saveTatItemList"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteBatchTatItem"></vxe-button>
              <!-- <div class="msgDiv">双击移除</div> -->
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <!--@cell-dblclick="tatItemRowClick"   双击移除-->
            <vxe-table ref="tatItemTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="qiTatVsItemList" :loading="ploading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="seq" title="序号" width="50"></vxe-column>
              <vxe-column field="itemNo" title="项目代码" width="50"></vxe-column>
              <vxe-column field="itemNa" title="项目名称" min-width="100"></vxe-column>
              <vxe-column field="rptGroupName" title="报告单元" width="100"></vxe-column>
              <vxe-column field="labTatDurat" title="实验室内规定周转时间" width="100" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.labTatDurat" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="checkTatDurat" title="检验前规定周转时间" width="100" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.checkTatDurat" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>
              <vxe-column field="totalTatDurat" title="总规定周转时间" width="100" :edit-render="{}">
                <template #edit="{ row, rowIndex, column }">
                  <vxe-input v-model="row.totalTatDurat" placeholder="" type="text"></vxe-input>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="30">

          <vxe-toolbar perfect>
            <template #buttons>
              <div class="smallToolTitle">报告单元</div>
              <vxe-select v-model="searchForm.rptGroup" :filterable="true" @change="valueChangeEvent" clearable>
                <vxe-option v-for="rptGroup in rptGroupList" :key="rptGroup.id" :value="rptGroup.rptGroup" :label="rptGroup.rptGroupName"></vxe-option>
              </vxe-select>
              <vxe-input style="width: 180px" v-model="searchForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findItemDictList" @keyup="keyupEnter" @search-click="findItemDictList()"></vxe-input>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="floading" @click="findItemDictList"></vxe-button>
              <!-- <div class="msgDiv">双击添加</div> -->
            </template>
          </vxe-toolbar>
          <div class="tableBody">
            <vxe-table ref="feeItemTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="itemDictList" :loading="floading" @cell-dblclick="itemDictRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column field="seq" title="序号" width="50"></vxe-column>
              <vxe-column field="itemNo" title="项目代码" width="50"></vxe-column>
              <vxe-column field="itemNa" title="项目名称" min-width="100"></vxe-column>
              <vxe-column field="rptGroupName" title="报告单元" width="100"></vxe-column>
            </vxe-table>
          </div>
          <vxe-pager align="left" min-height="32px" height="32px" :current-page.sync="page.currentPage" :page-size.sync="page.pageSize" :total="page.totalResult" :layouts="['PrevJump', 'PrevPage', 'Number', 'NextPage', 'NextJump', 'Sizes',  'Total']" @page-change="handleSizeChange($event)"></vxe-pager>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import { AppStore } from '@/stores/store';
let store = AppStore();

let tloading = ref(false); //刷新+表格加载
let sloading = ref(false); //刷新+表格加载
let floading = ref(false);
let ploading = ref(false);

let sltTatItemType: any = {};
let sltTatSpecItem: any = {};
let tatItemTypeList = reactive([]);
let tatSpecItemList = reactive([]);
let qiTatVsItemList = reactive([]);
let itemDictList = reactive([]);
let rptGroupList: any = reactive([]); //左侧仪器下拉项

let searchTatItemForm = {
  searchValue: ''
};

// 条数/页
const PageSizeList = [10, 50, 100, 200, 500];
// 分页
let page = reactive({
  currentPage: 1,
  pageSize: PageSizeList[1],
  totalResult: 0
});
onMounted(() => {
  findTatItemTypeList(); // 获取质控规则表格数据
  findTatSpecItemList();
  findRptGroupList();
});

function findRptGroupList() {
  rptGroupList.length = 0; //放入数据前清空数据
  const url = 'api/rptGroup/findRptGroup';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { seachValue: '' }
    })
    .then((res: any) => {
      rptGroupList.push(...res.data);
      // if (rptGroupList.length > 0) {
      //   searchForm.rptGroup = rptGroupList[0].rptGroup;
      // }
    })
    .catch((err: any) => {
      VxeMessage('获取左侧仪器表格数据异常', VxeNotifyType.error);
    });
}

function findTatItemTypeList() {
  tatItemTypeList.length = 0;
  tloading.value = true;
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'tatItemType' } })
    .then((res: any) => {
      if (res && res.data && res.data.length > 0) {
        tatItemTypeList.push(...res.data);
        if (tatItemTypeList.length > 0) {
          const kn = tatItemTypeList.find((k) => k.commonId == sltTatItemType.commonId);
          if (isEmpty(kn)) {
            tatItemTypeRowClick({ row: tatItemTypeList[0] });
          } else {
            tatItemTypeRowClick({ row: kn });
          }
        } else {
          sltTatItemType = {};
          qiTatVsItemList.length = 0;
        }
      } else {
        sltTatItemType = {};
        qiTatVsItemList.length = 0;
      }
      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      proxy.$alert(err, '提示');
    });
}

function tatItemTypeRowClick({ row }: any) {
  (proxy.$refs.tatItemTypeTableRef as any).setCurrentRow(row);
  sltTatItemType = row;
  proxy.$nextTick(() => {
    setTimeout(() => {
      (proxy.$refs.tatItemTypeTableRef as any).scrollToRow(row);
    }, 150);
  });
  findTatVsItemAndItemDictList();
}

function findTatSpecItemList() {
  sloading.value = true;
  tatSpecItemList.length = 0; //放入数据前清空数据
  const url = '/api/sys/basDictDetail/findDictDetailList';
  proxy.$http
    .get(url, { params: { code: 'tatSpecItem' } })
    .then((res: any) => {
      tatSpecItemList.push(...res.data);
      sloading.value = false;
      const kn = tatSpecItemList.find((k) => k.id == sltTatSpecItem.id);
      if (isEmpty(kn)) {
        tatSpecItemRowClick({ row: tatSpecItemList[0] }); //默认选中第一条数据
      } else {
        tatSpecItemRowClick({ row: kn }); //默认选中第一条数据
      }
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function tatSpecItemRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltTatSpecItem = {};
    qiTatVsItemList.length = 0;
  } else {
    (proxy.$refs.sampleTypeTableRef as any).setCurrentRow(row);
    sltTatSpecItem = row;
    findTatVsItemAndItemDictList();
  }
}

function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findItemDictList();
  }
}

let searchForm = reactive({
  rptGroup: '',
  searchValue: ''
});

function findItemDictList() {
  page.currentPage = 1;
  findLabItemDictPageByTat();
}

function findLabItemDictPageByTat() {
  floading.value = true;
  itemDictList.length = 0; //放入数据前清空数据
  const url = '/api/qi/qiTatVsItem/findLabItemDictPageByTat';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        seachValue: searchForm.searchValue,
        rptGroup: searchForm.rptGroup,
        tatTypeCode: sltTatItemType.code,
        tatItemCode: sltTatSpecItem.code,
        pageIndex: page.currentPage,
        pageSize: page.pageSize
      }
    })
    .then((res: any) => {
      if (res.data && res.data.records.length > 0) {
        itemDictList.push(...res.data.records);
        page.totalResult = res.data.total;
      } else {
        page.totalResult = 0;
      }
      floading.value = false;
    })
    .catch((err: any) => {
      floading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function findTatVsItemAndItemDictList() {
  if (!isEmpty(sltTatItemType.code) && !isEmpty(sltTatSpecItem.code)) {
    findItemDictList();
    findQiTatVsItemList();
  }
}

function findTatVsItemAndItemDicts(){
  if (!isEmpty(sltTatItemType.code) && !isEmpty(sltTatSpecItem.code)) {
    findLabItemDictPageByTat();
    findQiTatVsItemList();
  }
}

function itemDictRowClick({ row }: any) {
  if (isEmpty(sltTatItemType) || isEmpty(sltTatSpecItem)) {
    VxeMessage('请选择类型及具体项目', VxeNotifyType.error);
    return;
  }
  const url = '/api/qi/qiTatVsItem/addTatVsItem';
  let purposeItem = {
    tatTypeCode: sltTatItemType.code,
    tatItemCode: sltTatSpecItem.code,
    itemNo: row.itemNo,
    rptGroup: row.rptGroup,
    seq: row.seq
  };
  proxy.$http
    .post(url, purposeItem)
    .then((res: any) => {
      VxeMessage('成功', VxeNotifyType.success);
      findTatVsItemAndItemDicts();
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}
function keyupTatItemEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findQiTatVsItemList();
  }
}
function findQiTatVsItemList() {
  ploading.value = true;
  qiTatVsItemList.length = 0; //放入数据前清空数据
  const url = '/api/qi/qiTatVsItem/findQiTatVsItemList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchTatItemForm.searchValue,
        tatTypeCode: sltTatItemType.code,
        tatItemCode: sltTatSpecItem.code
      }
    })
    .then((res: any) => {
      qiTatVsItemList.push(...res.data);
      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

function tatItemRowClick({ row }: any) {
  const url = '/api/qi/qiTatVsItem/deleteTatVsItem';
  proxy.$http
    .post(url, row)
    .then((res: any) => {
      if (res.status.code === 1) {
        findTatVsItemAndItemDictList(); // 获取检验仪器表格数据
        VxeMessage('移除成功', VxeNotifyType.success);
      } else {
        VxeMessage(res.status.msg, VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      VxeMessage(err, VxeNotifyType.error);
    });
}
function valueChangeEvent() {
  findItemDictList();
}

function deleteBatchTatItem() {
  const sltTatItems = (proxy.$refs.tatItemTableRef as any).getCheckboxRecords();
  if (!(sltTatItems.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { qiTatVsItemList: sltTatItems };
        const url = '/api/qi/qiTatVsItem/batchDeleteTatItemList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            if (res.status.code === 1) {
              findTatVsItemAndItemDictList(); // 获取检验仪器表格数据
              VxeMessage('删除成功', VxeNotifyType.success);
            } else {
              VxeMessage(res.status.msg, VxeNotifyType.error);
            }
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}

async function saveTatItemList() {
  let $Xtable = proxy.$refs.tatItemTableRef;
  if ($Xtable) {
    // 表格实例表用该方法拿到有id的为修改
    const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
      return p.id && p.id !== '';
    });

    const sveOrupdateSamples = [] as any[];
    updateRecords.forEach((e: any) => {
      const iISample: any = {
        id: e.id,
        tatTypeCode: e.tatTypeCode,
        tatItemCode: e.tatItemCode,
        itemNo: e.itemNo,
        rptGroup: e.rptGroup,
        labTatDurat: e.labTatDurat,
        checkTatDurat: e.checkTatDurat,
        totalTatDurat: e.totalTatDurat,
        seq: e.seq
      };

      sveOrupdateSamples.push(iISample);
    });

    if (sveOrupdateSamples.length > 0) {
      const url = '/api/qi/qiTatVsItem/saveOrUpdateTatVsItem';
      const obj: any = {};
      obj.qiTatVsItemList = sveOrupdateSamples;
      proxy.$http
        .post(url, obj)
        .then((res: any) => {
          VxeMessage('更新成功', VxeNotifyType.success);
          setTimeout(() => {
            findQiTatVsItemList();
          }, 50);
        })
        .catch((err: any) => {
          VxeMessage('更新失败', VxeNotifyType.success);
        });
    } else {
      VxeMessage('无添加或修改数据', VxeNotifyType.error);
    }
  } else {
    return;
  }
}

function handleSizeChange({ type, currentPage, pageSize }) {
  if (type === 'size') {
    page.currentPage = 1;
  } else {
    page.currentPage = currentPage;
  }
  page.pageSize = pageSize;
  findLabItemDictPageByTat();
}
</script>

<style lang="scss" scoped>
#qiTatVsItemDiv {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .splitpanes {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .tableBody {
        height: calc(100% - 40px - 32px);
      }
      .msgDiv {
        margin-left: 5px;
        color: rgb(180, 28, 28);
      }
    }
  }
}
</style>